//
//  EssayViewController.m
//  shusheng
//
//  Created by rimi on 16/7/9.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "EssayViewController.h"

#import "NewCreatOneNovelViewController.h"


#import "NewEditorWord.h"
#import "NewCreateOneEorCViewController.h"
#import "NewCreatEssay.h"
#import "NewCreatOneChapter.h"

#import "EssayOfNet.h"

@interface EssayViewController ()<UITableViewDataSource,UITableViewDelegate,UIViewControllerTransitioningDelegate>

@property (weak, nonatomic) IBOutlet UISearchBar *listSearchbar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)EditorViewController *editorVC;

@property (atomic) NSInteger count;
@property (nonatomic,strong) NSDictionary *dic;
@property NSArray *dataArray;
@property (nonatomic,assign) BOOL isNetData;

@end

@implementation EssayViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.transitioningDelegate = self;
    self.modalPresentationStyle = UIModalPresentationCustom;
    
    
    if (!_isNovelList) {
        [self netData];

    }
    [self loadData];
    
    [self addRefresh];
    
    if (_dataArray.count == 0) {
        [MBProgressHUD showSuccess:@"暂无数据，可添加"];
    }
    
    
}

- (void)viewDidLayoutSubviews{
    [self loadData];
  
}
- (void)addRefresh{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
 
        for (int i = 0; i <_dataArray.count; i ++) {
            [_dataArray[i] removeAllObjects];
        }
        [self loadData];
        [self netData];
    }];
   
}


- (void)loadData{
    
    if (_isNovelList == NO) {
        NSLog(@"是文章列表");
        _titelLabel.text = @"文章列表";
        [self loadingDataWithEssay];//文章数据
        
    }else{
        
        NSLog(@"是小说列表");
        _titelLabel.text = _novelNameString;
        
        [self loadingDataWithNovelChapters];//小说数据
    }
}


/**<  文章数据 */
- (void)loadingDataWithEssay{
    
    _dataArray = [NewCreatEssay read];//本地
    NSLog(@"------本地count-----%lu",(unsigned long)_dataArray.count);
    
     _count = _dataArray.count;

    [_tableView reloadData];/**< ~~~~~~~~~~~~~~~~~~~~~~&***重要**& */
    [_tableView.mj_header endRefreshing];
    
}

/**< 小说章节数据 */
- (void)loadingDataWithNovelChapters{
    _dataArray = [NewCreatOneChapter readOfNovelId:_novelId];//根据小说ID获取,小说本地章节

    _count = _dataArray.count;
    NSLog(@"%lu",(unsigned long)_dataArray.count);
    [_tableView reloadData];
    [_tableView.mj_header endRefreshing];
    
}

#pragma make -- UIViewControllerTransitioningDelegate --
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypePresent];
}

-(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [AnimatedTransitioning transitionWithTransitionType:CircleSpreadTransitionTypeDismiss];
}
#pragma mark --  --
#pragma mark --
- (void)netData{
    [MBProgressHUD showSuccess:@"网络数据加载中"];
    
    __block NSInteger countOfPlist = _count;
    NSArray *netData = [[NSArray alloc]init];
    AVQuery *query = [AVQuery queryWithClassName:@"Essay"];
//    int uID = [[AVUser currentUser].objectId intValue];
    [query whereKey:@"userID" containsString:[AVUser currentUser].objectId];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
         NSLog(@"-----网络count-------%lu",(unsigned long)_dataArray.count);
        if (countOfPlist < objects.count) {
            _dataArray = objects;//使用网络数据
            _count = netData.count;
            [NewCreatEssay networkSynchronizationArray:objects];//存
            NSLog(@"-----网络count-------%lu",(unsigned long)_dataArray.count);
            [_tableView reloadData];/**< ~~~~~~~~~~~~~~~~~~~~~~&***重要**& */
            [_tableView.mj_header endRefreshing];
            [MBProgressHUD showSuccess:@"加载完成"];

        }
    }];
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate2 --
#pragma mark --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
//    return _count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EssayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EssayTableViewCell"];
    if (!cell) {
        cell = [[EssayTableViewCell alloc]init];
        
    }
    if (_isNovelList) {
        cell.titleLabel.text = _dataArray[indexPath.row][@"chapterName"];
         cell.timeLabel.text = _dataArray[indexPath.row][@"time"];
        
    }else{
        
//        if (_isNetData) {
//            cell.titleLabel.text = _dataArray[indexPath.row][@"essayName"];
//            cell.timeLabel.text = _dataArray[indexPath.row][@"time"];
//        }else{
            cell.titleLabel.text = _dataArray[indexPath.row][@"name"];
            cell.timeLabel.text = _dataArray[indexPath.row][@"time"];
//        }
        
    }
   
   
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"%ld",(long)indexPath.row);
    
    
    _editorVC = [self.storyboard instantiateViewControllerWithIdentifier:@"EditorViewController"];//编辑vc
    
    if (_isNovelList) {
        //小说
        
         _editorVC.titleNameSting = [NSString stringWithFormat:@"%@_%@",_novelNameString, _dataArray[indexPath.row][@"chapterName"]];
        
//        NSString *fileName = [NSString stringWithFormat:@"novelId=%@->chapterId=%@.txt",_dataArray[indexPath.row][@"novelId"],_dataArray[indexPath.row][@"chapterId"]];
//        _editorVC.fileName = fileName;
//        _editorVC.wordString = [NewEditorWord readFileName:fileName];
//
        
         NSString *f = _dataArray[indexPath.row][@"word"];
        _editorVC.fileName = f;
        _editorVC.wordString = [NewEditorWord readFileName:f];
        _editorVC.isNovel = YES;
        _editorVC.novelId = self.novelId;
        _editorVC.chapterId = _dataArray[indexPath.row][@"chapterId"];
        
   
    }else{
       //文章
         _editorVC.isNovel = NO;
         _editorVC.essayId = _dataArray[indexPath.row][@"essayId"];
         _editorVC.titleNameSting = [NSString stringWithFormat:@"%@",_dataArray[indexPath.row][@"name"]];

        NSString *f = _dataArray[indexPath.row][@"word"];
        _editorVC.fileName = f;
        _editorVC.wordString = [NewEditorWord readFileName:f];
        
        NSLog(@"~txt~内容~~~%@",[NewEditorWord readFileName:f]);

    }
    
    
    
    [self addChildViewController:_editorVC];
    [self.view addSubview:_editorVC.view];
    
}


#pragma mark -- UITableViewDelegate --
#pragma mark --
//是否允许编辑~默认yes
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//设置编辑样式~默认删除样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}


//修改删除确认按钮的标题
- (NSString * )tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";//~~默认是Delete;
}
//提交编辑样式~~~必须要实现的
//EditingStyle~~通过该参数来判断提交删除还是提交插入；
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        if (_isNovelList) {
            //删除章节
            
            //2删除txt数据
            [NewEditorWord deleteEditor:_dataArray[indexPath.row][@"word"]];
            //1删除列表源
            
            
            _dataArray = [NewCreatOneChapter deleteAChapterOfNovelId:self.novelId chapterId:_dataArray[indexPath.row][@"chapterId"] userId:_dataArray[indexPath.row][@"userId"]];
                        
            //删除单元行
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            
            
        }else{
            //删除文章
            
            //1.删除服务器
            NSString *objectId = _dataArray[indexPath.row][@"objectId"];
            [EssayOfNet deleteOneEssayOfObjectId:objectId];

            //2.删除txt数据
            [NewEditorWord deleteEditor:_dataArray[indexPath.row][@"word"]];
            
            //3.删除列表源
            _dataArray = [NewCreatEssay deleteSourceOfEssayId:_dataArray[indexPath.row][@"essayId"]];
            //4.删除单元行
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
           
                    }
    }
}



//移动~允许移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;//默认为NO
}
//移动操作
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    
    //数据源
    NSDictionary * dataCell = _dataArray[sourceIndexPath.row];
    NSMutableArray *marr = [NSMutableArray arrayWithArray:_dataArray];
    [marr removeObject:dataCell];
    [marr insertObject:sourceIndexPath atIndex:destinationIndexPath.row];
    _dataArray = [NSArray arrayWithArray:marr];
    
    //单元行
    [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
    
}

#pragma mark -- BtnAction --
#pragma mark --


- (IBAction)addBtn:(UIButton *)sender {
  
     NewCreateOneEorCViewController *newCreatVc = [self.storyboard instantiateViewControllerWithIdentifier:@"NewCreateOneEorCViewController"];
     newCreatVc.isNovelList = _isNovelList;
    
    if (_isNovelList) {
        newCreatVc.NovelNameString = _novelNameString;
        newCreatVc.novelId = _novelId;
        [self addChildViewController:newCreatVc];
        [self.view addSubview:newCreatVc.view];
        
    }else{
        
         NSLog(@"文章创建ing");
        
        
        [self addChildViewController:newCreatVc];
        [self.view addSubview:newCreatVc.view];
    }


    
}

- (void)deleteShow:(int)successOrError{
    
    switch (successOrError) {
        case 1:
            [MBProgressHUD showError:@"删除成功"];
            break;
        case 2:
            [MBProgressHUD showError:@"删除失败"];
            break;
        default:
            break;
    }
    
    
    
   
}

- (IBAction)order:(UIButton *)sender {
    //弹框选择排序方式
    //时间正序
    //时间逆序
    [MBProgressHUD showSuccess:@"暂无排序功能"];
}
- (IBAction)responBtn:(UIButton *)sender {
    NSLog(@"返回");
    if (_isNovelList) {
        [self removeFromParentViewController];
        [self.view removeFromSuperview];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}
@end
